package mo.tags.stack;

import java.util.Stack;

public class LV16_26 {

    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char pre = '+';
        StringBuilder builder = new StringBuilder();
        int len = s.length();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                builder.append(c);
            }
            if (!Character.isDigit(c) || i == len-1) {
                if (i != len - 1 && c == ' ') {
                    continue;
                }
                int cur = Integer.parseInt(builder.toString());
                if (pre == '+') {
                    stack.push(cur);
                } else if (pre == '-') {
                    stack.push(-cur);
                } else if (pre == '*') {
                    Integer pop = stack.pop();
                    stack.push(pop*cur);
                } else if (pre == '/') {
                    Integer pop = stack.pop();
                    stack.push(pop/cur);
                }
                builder.setLength(0);
                pre = c;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }

    public static void main(String[] args) {
        LV16_26 test = new LV16_26();
        System.out.println(test.calculate(" 3+5 / 2 "));
    }

}
